package com.itheima.tliaswebmanagement.service.impl;

import com.itheima.tliaswebmanagement.mapper.DeptMapper;
import com.itheima.tliaswebmanagement.mapper.EmpMapper;
import com.itheima.tliaswebmanagement.pojo.Dept;
import com.itheima.tliaswebmanagement.service.DeptService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service// 将当前类交给IOC容器管理,将来会成为IOC容器中的bean
public class DeptServiceImpl implements DeptService {
    private final SqlSessionFactory sqlSessionFactory;

    @Autowired
    public DeptServiceImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    /**
     * 查询所有部门数据
     *
     * @return List集合
     */
    @Override
    public List<Dept> list() {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            DeptMapper deptMapper = session.getMapper(DeptMapper.class);
            return deptMapper.list();
        }
    }

    /**
     * 根据id查询部门
     *
     * @param id id号
     * @return Dept对象
     */
    @Override
    public Dept selectById(Integer id) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            DeptMapper deptMapper = session.getMapper(DeptMapper.class);
            return deptMapper.selectById(id);
        }
    }

    /**
     * 根据id删除部门
     *
     * <p>
     * &#064;Transactional是Spring框架中的注解，用于将事务管理应用于方法或类。
     * 它使得开发者可以通过声明性的方式管理事务，而不需要手动处理事务的开启、提交和回滚等细节。
     * <br>
     * rollbackFor 属性用于指定当发生指定类型的异常时，事务应该进行回滚操作。
     * <br>
     * 默认情况下，只有出现`RuntimeException`才回滚异常。
     * </p>
     *
     * @param id id号
     */
    public void delete(Integer id) throws Exception {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
            EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
            deptMapper.delete(id);
            empMapper.deleteByDeptId(id);
        }
    }

    /**
     * 添加部门
     *
     * @param dept 部门对象
     */
    @Override
    public void insert(Dept dept) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
            dept.setCreateTime(LocalDateTime.now());
            dept.setUpdateTime(LocalDateTime.now());
            deptMapper.insert(dept);
        }
    }

    /**
     * 更新部门信息
     *
     * @param dept Dept对象
     */
    @Override
    public void update(Dept dept) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
            dept.setUpdateTime(LocalDateTime.now());
            deptMapper.update(dept);
        }
    }
}
